import { addQuestionUsingPost } from "@/api/questionController";
import { ProColumns, ProTable } from "@ant-design/pro-components";
import { message, Modal } from "antd";
import React from "react";

interface Props {
  visible: boolean;
  columns: ProColumns<API.Question>[];
  onSubmit: (values: API.QuestionAddRequest) => void;
  onCancel: () => void;
}

/**
 * 添加节点
 * @param fields
 */
const handleAdd = async (fields: API.QuestionAddRequest) => {
  const values = {
    title: "",
    content: "",
    answer: "",
    tags: [],
  };
  // @ts-ignore
  values.title = fields.title;
  // @ts-ignore
  values.content = fields.content;
  // @ts-ignore
  values.answer = fields.answer;
  // @ts-ignore
  values.tags = fields.tags;
  if (values.title?.trim() === "" || values.title === undefined) {
    message.error("请输入题目");
    return;
  } else if (values.content?.trim() === "" || values.content === undefined) {
    message.error("请输入内容");
    return;
  } else if (values.answer?.trim() === "" || values.answer === undefined) {
    message.error("请输入答案");
    return;
  } else if (values.tags == undefined || values.tags.length === 0) {
    message.error("请输入标签");
    return;
  } else {
    const hide = message.loading("正在添加", 25);
    try {
      await addQuestionUsingPost(fields);
      hide();
      message.success("创建成功");
      return true;
    } catch (error: any) {
      hide();
      message.error("创建失败，" + error.message);
      return false;
    }
  }
};

/**
 * 创建弹窗
 * @param props
 * @constructor
 */
const CreateModal: React.FC<Props> = (props) => {
  const { visible, columns, onSubmit, onCancel } = props;

  return (
    <Modal
      destroyOnClose
      title={"创建"}
      open={visible}
      footer={null}
      onCancel={() => {
        onCancel?.();
      }}
    >
      <ProTable
        type="form"
        columns={columns}
        onSubmit={async (values: API.QuestionAddRequest) => {
          const success = await handleAdd(values);
          // @ts-ignore
          if (success) {
            onSubmit?.(values);
          }
        }}
      />
    </Modal>
  );
};
export default CreateModal;
